﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;

using WeChatDemo.Models;
using WeChatDemo.Utils;
using AutoMapper;
using AutoMapper.Data;

namespace WeChatDemo.DataProvider
{
    public class DAOBase
    {
        public static readonly string _connectionString = WebConfigurationManager.AppSettings["sqlConnectionString"];

        //将DataReader映射为IEnumerable<T>
        protected static IEnumerable<T> ReaderToList<T>(string queryExpression, string tableName)
        {
            string _sqlString = $"SELECT * FROM {tableName} WHERE 1 = 1 {queryExpression}";

            Mapper.Reset();
            Mapper.Initialize(cfg =>
            {
                cfg.AddDataReaderMapping();

                cfg.CreateMap<IDataRecord, T>();
            });

            SqlDataReader _reader = SqlHelper.ExecuteReader(_connectionString, CommandType.Text, _sqlString);
            return Mapper.Map<IDataReader, IEnumerable<T>>(_reader);
        }

        //分页查询
        protected static IEnumerable<T> ReaderToList<T>(int pageSize, string queryExpression, string tableName)
        {
            string _sqlString = $"SELECT TOP {pageSize} * FROM {tableName} WHERE 1 = 1 {queryExpression}";

            Mapper.Reset();
            Mapper.Initialize(cfg =>
            {
                cfg.AddDataReaderMapping();

                cfg.CreateMap<IDataRecord, T>();
            });

            SqlDataReader _reader = SqlHelper.ExecuteReader(_connectionString, CommandType.Text, _sqlString);
            return Mapper.Map<IDataReader, IEnumerable<T>>(_reader);
        }

    }
}